const express = require('express')
const { readFileSync, writeFileSync } = require("fs");
const { resolve } = require("path");
const router = express.Router()

router.post("/update_schedule", (req, res) => {
    const { begin_time, course, teacher, weekday } = req.body.data;
    console.log(begin_time, course, teacher, weekday);

    const schedule = JSON.parse(
        readFileSync(resolve(__dirname, "../../data/course/schedule.json"), "utf8")
    );
    const item = schedule.find(
        (item) => item.begin_time == begin_time && item.weekday == weekday
    );

    let type = "";
    let result = null;
    if (item) {
        item.course = course;
        item.teacher = teacher;
        result = item;
        type = "EDIT";
    } else {
        let lastID = schedule[schedule.length - 1]
            ? schedule[schedule.length - 1].id
            : 1;
        const newData = {
            id: ++lastID,
            begin_time,
            course,
            teacher,
            weekday,
        };
        schedule.push(newData);
        result = newData;
        type = "ADD";
    }
    writeFileSync(
        resolve(__dirname, "../../data/course/schedule.json"),
        JSON.stringify(schedule)
    );
    res.json({
        code: 200,
        msg: "数据写入成功",
        data: {
            type,
            result,
        },
    });
});

router.post("/remove_schedule", (req, res) => {
    const id = req.body.id;
    const schedule = JSON.parse(
        readFileSync(resolve(__dirname, "../../data/course/schedule.json"), "utf8")
    );

    const newSchedule = schedule.filter((item) => item.id != id);
    writeFileSync(
        resolve(__dirname, "../../data/course/schedule.json"),
        JSON.stringify(newSchedule)
    );
    res.json({
        code: 200,
        msg: "数据删除成功",
        data: {
            type: "REMOVE",
            id,
        },
    });
});

module.exports = router